package ceshi;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;

//Team 类定义了一个足球队伍，包含队伍名称、比赛场次、胜负平次数、进球失球数和积分
class Team {
    String name;
    int matchesPlayed;
    int wins;
    int draws;
    int losses;
    int goalsScored;
    int goalsConceded;
    int points;

    Team(String name, int matchesPlayed, int wins, int draws, int losses, int goalsScored, int goalsConceded, int points) {
        this.name = name;
        this.matchesPlayed = matchesPlayed;
        this.wins = wins;
        this.draws = draws;
        this.losses = losses;
        this.goalsScored = goalsScored;
        this.goalsConceded = goalsConceded;
        this.points = points;
    }
 // 根据主客场更新进球和失球数
    void update(int homeScore, int awayScore, boolean isHome) {
        if (isHome) {
            this.goalsScored += homeScore;
            this.goalsConceded += awayScore;
        } else {
            this.goalsScored += awayScore;
            this.goalsConceded += homeScore;
        }

        if ((isHome && homeScore > awayScore) || (!isHome && awayScore > homeScore)) {
            this.wins++;
            this.points += 3;
        } else if (homeScore == awayScore) {
            this.draws++;
            this.points += 1;
        } else {
            this.losses++;
        }

        this.matchesPlayed++;
    }
//统计净胜球，用于积分相同时进行排名
    int getNetGoals() {
        return this.goalsScored - this.goalsConceded;
    }

    @Override
    public String toString() {
        return String.format("%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d",
                this.name, this.matchesPlayed, this.wins, this.draws, this.losses,
                this.goalsScored, this.goalsConceded, this.points);
    }
}

public class FootballLeague {
    public static void main(String[] args) {
        List<Team> teams = new ArrayList<>();
        try {
            readTeamsFromFile(teams, "C:\\Users\\admin\\eclipse-workspace\\ceshi\\src\\ceshi\\league_table.txt");//使用绝对路径
        } catch (IOException e) {
            System.err.println("读取联赛排名表文件时出错: " + e.getMessage());
            return;
        }

        Scanner scanner = new Scanner(System.in);
        boolean continueInput = true;

        while (continueInput) {
            System.out.println("请输入比赛结果 (输入 'exit' 退出):");//开始第一次可输入exit退出，不退出就回车用来输入比赛比分

            String command = scanner.nextLine().trim().toLowerCase();
            if ("exit".equals(command)) {
                continueInput = false;
                break;
            }

            String homeTeamName = getValidTeamName(scanner, teams, "主队名称: ");
            if (homeTeamName == null) {
                continue;
            }

            String awayTeamName = getValidTeamName(scanner, teams, "客队名称: ");
            if (awayTeamName == null) {
                continue;
            }

            int homeScore = getValidScore(scanner, "主队比分: ");
            if (homeScore == -1) {
                continue;
            }

            int awayScore = getValidScore(scanner, "客队比分: ");
            if (awayScore == -1) {
                continue;
            }

            Optional<Team> homeTeamOpt = teams.stream().filter(team -> team.name.equals(homeTeamName)).findFirst();
            Optional<Team> awayTeamOpt = teams.stream().filter(team -> team.name.equals(awayTeamName)).findFirst();

            if (homeTeamOpt.isPresent() && awayTeamOpt.isPresent()) {
                Team homeTeam = homeTeamOpt.get();
                Team awayTeam = awayTeamOpt.get();

                homeTeam.update(homeScore, awayScore, true);
                awayTeam.update(homeScore, awayScore, false);
            } else {
                System.out.println("联赛排名表中未找到一支或两支队伍。");
                continue;
            }
//首先比较积分（points），如果积分相同，则比较净胜球（通过调用 getNetGoals 方法），如果净胜球也相同，则最后比较进球数。
            teams.sort((t1, t2) -> {
                int pointsComparison = Integer.compare(t2.points, t1.points);
                if (pointsComparison != 0) {
                    return pointsComparison;
                }
                int netGoalsComparison = Integer.compare(t2.getNetGoals(), t1.getNetGoals());
                if (netGoalsComparison != 0) {
                    return netGoalsComparison;
                }
                return Integer.compare(t2.goalsScored, t1.goalsScored);
            });

            System.out.println("更新后的联赛排名:");
            System.out.println("队伍名称\t场次\t胜\t平\t负\t进球\t失球\t积分");
            teams.forEach(team -> System.out.println(team));

            try {
                writeUpdatedTableToFile(teams, "C:\\Users\\admin\\eclipse-workspace\\ceshi\\src\\ceshi\\league_table.txt");//使用绝对路径
            } catch (IOException e) {
                System.err.println("写入更新后的联赛排名表文件时出错: " + e.getMessage());
            }
        }

        scanner.close();
    }
    // 从文件读取队伍信息的方法
    private static void readTeamsFromFile(List<Team> teams, String filePath) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            br.readLine(); // Skip header
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\t");
                teams.add(new Team(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3]),
                        Integer.parseInt(parts[4]), Integer.parseInt(parts[5]), Integer.parseInt(parts[6]), Integer.parseInt(parts[7])));
            }
        }
    }
 // 获取有效的队伍名称的方法
    private static String getValidTeamName(Scanner scanner, List<Team> teams, String prompt) {
        System.out.print(prompt);
        String teamName = scanner.nextLine();
        Optional<Team> teamOpt = teams.stream()
                .filter(team -> team.name.equals(teamName))
                .findFirst();
        if (teamOpt.isPresent()) {
            return teamOpt.get().name;
        } else {
            System.out.println("输入的队伍名称不存在，请重新输入。");
            return getValidTeamName(scanner, teams, prompt); // Recursive call
        }
    }
 // 获取有效的比分的方法
    private static int getValidScore(Scanner scanner, String prompt) {
        System.out.print(prompt);
        while (true) {
            try {
                return scanner.nextInt();
            } catch (NumberFormatException e) {
                System.out.println("输入的比分必须是整数，请重新输入。");
                scanner.nextLine(); // Clear the invalid input
            }
        }
    }
 // 将更新后的联赛排名写回文件的方法
    private static void writeUpdatedTableToFile(List<Team> teams, String filePath) throws IOException {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) {
            bw.write("队伍名称\t场次\t胜\t平\t负\t进球\t失球\t积分\n");
            for (Team team : teams) {
                bw.write(team.toString());
                bw.newLine();
            }
        }
    }
}